#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <windows.h>

int high,width;    // 画面尺寸 
int ball_x,ball_y;//小球位置
int ball_vx,ball_vy;//小球速度 
int position_x,position_y;//挡板中心坐标
int radius;//挡板半径
int left,right;//挡板左右边界 
int ball_number; 

void HideCursor()
{
	CONSOLE_CURSOR_INFO cursor_info = {1, 0};
	SetConsoleCursorInfo (GetStdHandle (STD_OUTPUT_HANDLE), &cursor_info);
}

void gotoxy(int x,int y)
{
	HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X=x;
	pos.Y=y;
	SetConsoleCursorPosition(handle,pos);
}

void startup()
{
	high=24;
	width=36;
	
	ball_x=1;
	ball_y=width/2;
	ball_vx=1;
	ball_vy=1;
	
	position_x=high;
	position_y=width/2;
	radius=4;
	left=position_y-radius;
	right=position_y+radius;
	
	ball_number=0;

	HideCursor(); 
}

void show()
{
	gotoxy(0,0);
	int i,j;
	
	for(i=0;i<=high+1;i++)
	{
		for(j=0;j<=width;j++)
		{
			if((i==ball_x)&&(j==ball_y))//输出一个小球 
			{
				printf("o");
			}
			else if(i==high+1)//下边界 
			{
				printf("-");
			}
			else if(j==width)//右边界 
			{
				printf("||");
			}
			else if(i==high&&j>=left&&j<=right)//输出挡板 
			{
				printf("*");
			}
			else if((i==0)&&(j==20))
			{
				if(ball_x==0&&ball_y==20)//输出目标	+判断击中后目标消失 
				{
					printf(" ");
				}
				else
				{
					printf("$"); 
				}
				
			}
			
			else
			{
				printf(" ");
			}
			
		}
		printf("\n");
	}
	printf("反弹小球数：%d\n",ball_number);
}


void updatewithoutinput()
{
	//减慢小球速度
	static int speed=0;
	
	if(speed<10)
	{
		speed++;
	}
	if(speed==10)
		{
		if(ball_x==high-1)
			{
				if(ball_y>=left&&ball_y<=right)
				{
				ball_number=ball_number+1;//加分 
				}
				else
				{
					printf("Game Over");//游戏结束 
					exit(0);
					system("pause");
				}
			}
				//更新小球位置 
			ball_x=ball_x+ball_vx; 
			ball_y=ball_y+ball_vy;
			
				//碰到边界
			if((ball_x==0)||(ball_x==high-1)) 
				{
					ball_vx=-1*ball_vx;
				}
			if((ball_y==0)||(ball_y==width-1)) 
				{
					ball_vy=-1*ball_vy;
				}
			speed=0;
			
	
	}		
	
}



void updatewithinput()
{
	char input;
	if(kbhit())
	{
		input=getch();
		
		if(input=='a')
		{
			position_y--;
			left=position_y-radius;
			right=position_y+radius;

		}
		if(input=='d')
		{
			position_y++;
			left=position_y-radius;
			right=position_y+radius;

		}
		
	}	
	

}



int main()
{
	startup();
	while(1)
	{
		show();
		updatewithoutinput();
		updatewithinput();
	}
	return 0;
}